package com.sy.service.message.impl;

import com.alibaba.excel.EasyExcel;
import com.sy.bean.message.Goods;
import com.sy.bean.message.GoodsCategory;
import com.sy.bean.message.excel.GoodsExcel;
import com.sy.common.crud.BaseServiceImpl;
import com.sy.common.exception.BusinessException;
import com.sy.mapper.message.GoodsMapper;
import com.sy.mapper.message.GoodsSpecMapper;
import com.sy.service.message.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;

@Service
public class GoodsServiceImpl extends BaseServiceImpl<Goods, GoodsMapper> implements GoodsService {
    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    GoodsSpecMapper goodsSpecMapper;

    @Autowired
    HttpServletRequest request;

    @Override
    @Transactional
    public int save(Goods entity) {
        int rs=goodsMapper.save(entity);
        if (rs==0){
            throw new BusinessException("保存商品失败");
        }
        //保存商品规格详情
        rs=goodsSpecMapper.batchSave(entity.getId(),entity.getGoodsSpecList());
        if (rs==0){
            throw new BusinessException("保存商品规格失败");
        }
        return 1;
    }

    @Override
    public int updateDetail(int id, String goodsDetail) {
        return goodsMapper.updateDetail(id,goodsDetail);
    }

    @Override
    public int delById(int id) {
        return goodsMapper.delById(id);
    }

    @Override
    public String exportGoods(Map map) {
        List<GoodsExcel> list = goodsMapper.exportGoods(map);
        String root = request.getServletContext().getRealPath("/") + "/excel";
        File file = new File(root);
        if (!file.exists())
            file.mkdirs();
        String newFileName = file.getAbsolutePath() + "/商品列表.xlsx";
        EasyExcel.write(newFileName, GoodsExcel.class)
                .sheet("订单列表")
                .doWrite(() -> {
                    return list;
                });
        return "/excel/商品列表.xlsx";
    }
}
